package com.yxinmiracle.order.service.impl;

import com.yxinmiracle.goods.feign.SkuFeign;
import com.yxinmiracle.goods.feign.SpuFeign;
import com.yxinmiracle.goods.pojo.Sku;
import com.yxinmiracle.goods.pojo.Spu;
import com.yxinmiracle.order.pojo.OrderItem;
import com.yxinmiracle.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @version 1.0
 * @author： YxinMiracle
 * @date： 2021-08-18 09:47
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private SpuFeign spuFeign;

    @Override
    public void add(Integer num, Long id, String username) {
        if (num<0){
            redisTemplate.boundHashOps("Cart_"+username).delete(id);
            return;
        }
        Sku data = skuFeign.findById(id).getData();
        OrderItem orderItem = new OrderItem();
        Spu spu = spuFeign.findById(data.getSpuId()).getData();
        orderItem.setImage(data.getImage());
        orderItem.setPrice(data.getPrice());
        orderItem.setSkuId(data.getId());
        orderItem.setSpuId(data.getSpuId());
        orderItem.setName(data.getName());
        orderItem.setNum(num);
        orderItem.setMoney(num*data.getPrice());
        orderItem.setPayMoney(num*data.getPrice());
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());
        redisTemplate.boundHashOps("Cart_"+username).put(id,orderItem);
    }

    @Override
    public List<OrderItem> list(String username) {
        return redisTemplate.boundHashOps("Cart_" + username).values();

    }
}
